package com.leo.javase.thread.itcast;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableAndFuture {

	public static void main(String[] args) {
		
		//new CallableAndFuture().method1();
		
		new CallableAndFuture().method2();
		
	}
	/**
	 * 提交callable任务
	 */
	public void method1(){
		ExecutorService pool = Executors.newSingleThreadExecutor();
		//提交callable的任务
		Future<String> future = pool.submit(new Callable<String>(){
			@Override
			public String call() throws Exception {
				Thread.sleep(2000);
				return "hello";
			}
		});
		
		System.out.println("等待结果:");
		try {
			System.out.println(future.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 提交一组callable任务
	 */
	public void method2(){
		//创建线程池
		ExecutorService pool = Executors.newFixedThreadPool(10);
		//
		CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(pool);
		
		//提交10个callable任务
		for(int i=1; i<=10; i++){
			final int seq = i;
			completionService.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					return seq;
				}
			});
		}
		
		//提取结果
		for(int i=0; i<10; i++){
			try {
				System.out.println(completionService.take().get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}

}
